/**
 * Created by sun.kang on 14-5-26.
 */
var GamePlayScene = cc.Scene.extend ({
    space:null,
    shapesToRemove: [],

    onEnter : function () {
        this._super();
        this.initPhysics();

        this.shapesToRemove = [];

        this.addChild(new BackgroundLayer(this.space), 0, TagOfLayer.Background);
        this.addChild(new AnimationLayer(this.space), 0, TagOfLayer.Animation);
        this.addChild(new StatusLayer(), 0, TagOfLayer.Status);

//        var audioEngine = cc.AudioEngine.getInstance();
        cc.audioEngine.playMusic(res.Background_ogg, true);

        this.scheduleUpdate();
    },

    initPhysics: function () {
        this.space = new cp.Space();
        this.space.gravity = cp.v(0, -350);

        var wallBottom = new cp.SegmentShape(this.space.staticBody,
            cp.v(0, g_groundHeight),
            cp.v(Math.pow(2,32) - 1, g_groundHeight),
            0);

        this.space.addStaticShape(wallBottom);

        this.space.addCollisionHandler(SpriteTag.runner, SpriteTag.coin,
            this.collisionCoinBegin.bind(this), null, null, null);

        // this.collisionRockBegin.bind(this)和this.collisionRockBegin的区别是什么？？？
        this.space.addCollisionHandler(SpriteTag.runner, SpriteTag.rock,
            this.collisionRockBegin.bind(this), null, null, null);
            // this.collisionRockBegin, this.testPreSolve, this.testPostSolve, this.testSeperate);
            // this.collisionRockBegin.bind(this), this.testPreSolve.bind(this), this.testPostSolve.bind(this), this.testSeperate.bind(this));

    },

    collisionCoinBegin: function (arbiter, space) {
        var shapes = arbiter.getShapes();
        this.shapesToRemove.push(shapes[1]);

        var statusLayer = this.getChildByTag(TagOfLayer.Status);
        statusLayer.addCoin(1);

//        var audioEngine = cc.AudioEngine.getInstance();
        cc.audioEngine.playEffect(res.PickUpCoin_ogg);
    },

    collisionRockBegin: function (arbiter, space) {
        cc.log("==game over");
//        var audioEngine = cc.AudioEngine.getInstance();
        cc.audioEngine.stopMusic();
        cc.director.pause();
        this.addChild(new GameOverLayer());
    },

//    testPreSolve: function (arbiter, space) {
//        cc.log("==Pre Solve");
//    },
//
//    testPostSolve: function (arbiter, space) {
//        cc.log("==Post Solve");
//    },
//
//    testSeperate: function (arbiter, space) {
//        cc.log("==Seperate");
//    },

    update: function (dt) {
        this.space.step(dt);

        for (var i = 0; i < this.shapesToRemove.length; i ++) {
            var shape = this.shapesToRemove[i];
            this.getChildByTag(TagOfLayer.Background).removeObjectByShape(shape);
        }

        this.shapesToRemove = [];
    }
});